package com.ec50n9.server.module.role

import com.ec50n9.server.common.render
import com.ec50n9.server.module.common.CreateForm
import com.ec50n9.server.module.common.Render
import com.ec50n9.server.module.common.Rendered
import com.ec50n9.server.module.common.UpdateForm
import com.ec50n9.server.module.resource.Resource
import com.ec50n9.server.module.user.User
import org.hibernate.annotations.GenericGenerator
import javax.persistence.*
import javax.validation.constraints.NotBlank

@Entity
class Role(
    @Column(unique = true)
    var name: String,

    @Column(unique = true)
    var code: String,

    @ManyToMany(mappedBy = "roles")
    var users: MutableSet<User> = mutableSetOf(),

    @ManyToMany(fetch = FetchType.EAGER)
    var resources: MutableSet<Resource> = mutableSetOf(),

    @Id
    @GenericGenerator(name = "nanoid", strategy = "com.ec50n9.server.common.NanoIdGenerator")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "nanoid")
    var id: String? = null
) : Render<Role>()

/**
 * 创建角色表单
 */
data class RoleCreateForm(
    @field: NotBlank(message = "角色名不能为空")
    var name: String? = null,
    @field: NotBlank(message = "角色代码不能为空")
    var code: String? = null
) : CreateForm<Role> {
    override fun renderTo(): Role {
        val role = Role("", "")
        render(role)
        return role
    }
}

/**
 * 角色更新表单
 */
data class RoleUpdateForm(
    var name: String? = null,
    var code: String? = null
) : UpdateForm<Role> {
    override fun renderTo(target: Role) {
        render(target, true)
    }
}

/**
 * 查询渲染
 */
data class RoleQueryRendered(
    var name: String? = null,
    var code: String? = null,
) : Rendered<Role> {
    override fun renderFrom(from: Role) {
        from.render(this)
    }
}
